// routes/auth.js  
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const Counter = require('../models/counter');

// 假设你有一个SECRET_KEY环境变量来存储JWT密钥  
const SECRET_KEY = process.env.SECRET_KEY || 'your-secret-key';

// 注册接口  
router.post('/register', async (req, res) => {
    try {
        const { userName, password, phoneNumber, email, gender, post, departmentId, remark, role, state, userNickname } = req.body;
        const counter = await Counter.findOneAndUpdate(
            { _id: 'userId' }, // 序列标识
            { $inc: { seq: 1 } },
            { new: true, upsert: true } // 不存在时自动创建
        );
        // 创建新用户并保存  
        const newUser = new User({ userId: counter.seq, userName, password, phoneNumber, email, gender, post, departmentId, remark, role, state, userNickname });
        await newUser.save();
        res.json({ message: '操作成功' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '操作失败' });
    }
});

// 登录接口  
router.post('/login', async (req, res) => {
    try {
        const { userId, password } = req.body;

        // 检查用户名和密码是否已提供  
        if (!userId || !password) {
            return res.status(200).json({ code: -1, data: { message: '账号和密码必须同时提供' } });
        }

        // 查找用户  
        const user = await User.findOne({ userName: userId });
        if (!user) {
            return res.status(200).json({ code: -1, data: { message: '未找到当前用户' } });
        }

        // 验证密码  
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(200).json({ code: -1, data: { message: '密码错误' } });
        }

        // 生成JWT令牌并返回  
        const token = jwt.sign({ id: user._id }, SECRET_KEY, { expiresIn: '1h' });
        res.json({ code: 0, data: { token, userId: user.userId, userName: user.userName } });
    } catch (error) {
        res.status(500).json({ code: -1, data: { message: '操作失败' } });
    }
});

// 查询所有英雄信息路由
router.get("/user", async (req, res) => {
    try {
        // 搜索条件
        let filter = {};
        if (req.query.phoneNumber) {
            filter.phoneNumber = { $regex: req.query.phoneNumber, $options: 'i' };
        }
        if (req.query.userName) {
            filter.userName = { $regex: req.query.userName, $options: 'i' };
        }
        if (req.query.state) {
            filter.state = req.query.state;
        }
        if (req.query.deptId) {
            filter.departmentId = req.query.deptId;
        }
        if (req.query.createdAt) {
            filter.createdAt = { $gte: JSON.parse(req.query.createdAt)[0], $lte: JSON.parse(req.query.createdAt)[1] };
        }
        // 获取请求中的分页参数，默认值处理
        const currentPage = parseInt(req.query.currentPage) || 1;
        const limit = parseInt(req.query.pageSize) || 10;
        // 添加排序逻辑，这里假设按joinedDate字段降序排序
        const sortOption = req.query.sortBy === 'asc' ? { createdAt: 1 } : { createdAt: -1 };
        // 计算跳过的文档数量
        const skip = (currentPage - 1) * limit;
        const user = await User.find(filter).populate("departmentId", "deptName").skip(skip).limit(limit).sort(sortOption)
        const total = await User.countDocuments(filter);
        res.send({ page: { total, currentPage, pageSize: limit }, result: user });
    } catch (err) {
        res.status(500).send({ error: '查询失败', err });
    }
});
//更新一条用户信息数据路由
router.put("/user", async (req, res) => {
    try {
        const updatedUser = await User.findByIdAndUpdate(req.body.id, { departmentId: req.body.deptId, ...req.body }, { new: true });
        if (!updatedUser) return res.status(404).send({ error: '没有找到此用户' });
        res.send({ message: "操作成功" });
    } catch (err) {
        res.status(500).send({ error: '操作失败' });
    }
});
//删除一条英雄信息路由
router.delete("/user", async (req, res) => {
    try {
        // 从查询参数中获取id
        const id = req.query.id;
        if (!id) {
            return res.status(400).send({ error: 'Missing "id" query parameter' });
        }
        await User.findByIdAndDelete(id);
        res.send({ message: '删除成功' });
    } catch (err) {
        if (err.name === 'CastError') return res.status(404).send({ error: '未找到当前用户' });
        res.status(500).send({ error: '删除失败' });
    }
});

module.exports = router;